import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/entity/match/zq_match_event_entity.dart';
import 'package:ball_lion/entity/match/zq_match_info_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/utils/match_zq_utils.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/module/match_detail/soccer/zq_nodata_widget.dart';

import 'package:ball_lion/widgets/base/wqs_text.dart';

class ZqSitch extends StatefulWidget {
  const ZqSitch(
      {super.key, this.value = true, this.activeColor, this.onChanged});

  final Color? activeColor;
  final bool value;
  final void Function(bool v)? onChanged;

  @override
  State<ZqSitch> createState() => _ZqSitchState();
}

class _ZqSitchState extends State<ZqSitch> {
  bool get value => widget.value;

  @override
  Widget build(BuildContext context) {
    const duration = Duration(milliseconds: 100);
    return AnimatedContainer(
      duration: duration,
      width: 40,
      height: 24,
      decoration: BoxDecoration(
          color: value ? Colours.main : Colours.greyF7,
          borderRadius: BorderRadius.circular(14.5)),
      child: Row(
        children: [
          AnimatedContainer(width: value ? 18 : 2, duration: duration),
          AnimatedOpacity(
            opacity: value ? 1 : 0.5,
            duration: duration,
            child: Container(
                decoration: const BoxDecoration(
                    shape: BoxShape.circle, color: Colors.white),
                child: Image.asset(Utils.getImgPath("match_icon_jinqiu.png"),
                    width: 20, height: 20)),
          )
        ],
      ),
    ).tap(() {
      widget.onChanged?.call(!value);
    });
  }
}

class ZqMilestoneWidget extends StatefulWidget {
  const ZqMilestoneWidget({super.key, required this.events, this.match});

  final List<ZqMatchEventEntity> events;
  final ZqMatchInfoEntity? match;

  @override
  State<ZqMilestoneWidget> createState() => _MilestoneWidgetState();
}

class ZqEventModel {
  ZqEventModel(this.eventTime, this.isHome, this.eventType, this.eventContent);
  final String eventTime;
  final bool isHome;
  final int eventType;
  final String? eventContent;

  static List<ZqEventModel> getFromEntity(ZqMatchEventEntity event) {
    //1 : 进球  2 : 红牌  3 : 黄牌  37 : 罚失点球  7 : 点球  8 : 乌龙   9 : 两黄变红  11 : 换人  14 : VAR 21 : 助攻
    List<ZqEventModel> list = [];
    switch (event.kind) {
      case 1:
        list.add(ZqEventModel(event.eventTime ?? "", (event.isHome ?? 0) > 0,
            ZqEvent.jinQiu, event.playerCh));
        break;
      case 2:
        list.add(ZqEventModel(event.eventTime ?? "", (event.isHome ?? 0) > 0,
            ZqEvent.hongPai, event.playerCh));
        break;
      case 3:
        list.add(ZqEventModel(event.eventTime ?? "", (event.isHome ?? 0) > 0,
            ZqEvent.huangPai, event.playerCh));
        break;
      case 37:
        list.add(ZqEventModel(event.eventTime ?? "", (event.isHome ?? 0) > 0,
            ZqEvent.fanGuiDianQiu, event.playerCh));
        break;
      case 7:
        list.add(ZqEventModel(event.eventTime ?? "", (event.isHome ?? 0) > 0,
            ZqEvent.dianQiu, event.playerCh));
        break;
      case 8:
        list.add(ZqEventModel(event.eventTime ?? "", (event.isHome ?? 0) > 0,
            ZqEvent.wuLong, event.playerCh));
        break;
      case 9:
        list.add(ZqEventModel(event.eventTime ?? "", (event.isHome ?? 0) > 0,
            ZqEvent.liangHuang, event.playerCh));
        break;
      case 11:
        final arr = event.playerCh?.split(RegExp("[↑↓]"))
          ?..removeWhere((element) => element.isEmpty);
        list.add(ZqEventModel(event.eventTime ?? "", (event.isHome ?? 0) > 0,
            ZqEvent.huanShang, arr?.first ?? ""));
        list.add(ZqEventModel(event.eventTime ?? "", (event.isHome ?? 0) > 0,
            ZqEvent.huanXia, arr?.last ?? ""));
        break;
      case 13:
        list.add(ZqEventModel(event.eventTime ?? "", (event.isHome ?? 0) > 0,
            ZqEvent.sheShiDianQiu, event.playerCh));
        break;
      case 14:
        list.add(ZqEventModel(event.eventTime ?? "", (event.isHome ?? 0) > 0,
            ZqEvent.theVar, event.playerCh));
        break;
      case 53:
        list.add(ZqEventModel(
            event.eventTime ?? event.halfScore ?? event.allScore ?? "",
            (event.isHome ?? 0) > 0,
            ZqEvent.banChangJieShu,
            event.playerCh));
        break;
      case 5:
        list.add(ZqEventModel(
            event.eventTime ?? event.halfScore ?? event.allScore ?? "",
            (event.isHome ?? 0) > 0,
            ZqEvent.jieShu,
            event.playerCh));
        break;
      case 21:
        list.add(ZqEventModel(
            event.eventTime ?? event.halfScore ?? event.allScore ?? "",
            (event.isHome ?? 0) > 0,
            ZqEvent.zhuGong,
            event.playerCh));
        break;
      default:
        log("ignore event ${event.kind}");
    }
    return list;
  }
}

class _MilestoneWidgetState extends State<ZqMilestoneWidget> {
  bool onlyScore = false;

  ZqMatchInfoEntity? get info => widget.match;

  get match => widget.match;
  // List<ZqMatchEventEntity> get events => widget.events;
  late List<ZqMatchEventEntity> importantEventList;
  late List<ZqMatchEventEntity> goalEventList;

  @override
  void initState() {
    super.initState();
    importantEventList = List.from(widget.events);
    importantEventList.removeWhere((element) =>
        !ZqMilestoneUtils.importantEventId.contains(element.kind ?? 0));

    goalEventList = List.from(importantEventList);
    goalEventList.removeWhere((element) =>
        element.kind != 1 &&
        element.kind != 5 &&
        element.kind != 53 &&
        element.kind != 7 &&
        element.kind != 8);
  }

  List<List<ZqEventModel>> makeEventsList({bool beforeHalf = true}) {
    final list = List<List<ZqEventModel>>.generate(0, (index) => []);

    final events1 =
        onlyScore ? List.from(goalEventList) : List.from(importantEventList);
    var time = "";
    for (var i = 0; i < events1.length; i++) {
      final e = events1[i];
      if (e.eventTime == time) {
        list.last.addAll(ZqEventModel.getFromEntity(e));
      } else {
        time = e.eventTime ?? "";
        list.add(ZqEventModel.getFromEntity(e));
      }
    }
    return list;
  }

  String? get halfScore => info?.halfScoreRate;
  bool get isMatchFinish => info?.isMatchFinish ?? false;

  @override
  Widget build(BuildContext context) {
    if (importantEventList.isEmpty) {
      return ZqNodataWidget(info: info);
    }
    final datalist1 = makeEventsList(beforeHalf: true);
    return Container(
      color: Colors.white,
      child: Column(
        children: [
          const SizedBox(height: 24),
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Expanded(child: Container()),
              Image.asset(Utils.getImgPath("match_icon_start.png"),
                  width: 20, height: 20, fit: BoxFit.fill),
              Expanded(
                  child: Row(
                children: [
                  const SizedBox(width: 5),
                  QsText("开始", color: Colours.grey99, fontSize: 12),
                  const Spacer(),
                  _top(),
                ],
              )),
            ],
          ),
          ListView.builder(
            padding: EdgeInsets.zero,
            shrinkWrap: true,
            physics: ClampingScrollPhysics(),
            itemCount: datalist1.length,
            itemBuilder: ((context, index) {
              final list = datalist1[index];
              bool hasBottom = index < (datalist1.length - 1);
              if (halfScore == null && datalist1.length == index + 1) {
                hasBottom = false;
              }
              // log("build $index length ${list.length} ${list.first.eventContent}");
              return _timeCell(true, hasBottom, list);
            }),
          ),
          // _footer(),
          _iconWidget()
        ],
      ),
    );
  }

  Widget eventSideCard(List<Widget> children, {bool left = true}) => children
          .isEmpty
      ? Container()
      : Stack(
          alignment: left ? Alignment.centerRight : Alignment.centerLeft,
          children: [
            Container(
              padding: const EdgeInsets.all(7.5),
              margin:
                  const EdgeInsets.only(top: 16, bottom: 16, left: 2, right: 2),
              decoration: BoxDecoration(
                  color: Colours.white,
                  border: Border.all(color: Colours.greyEE, width: 0.5),
                  borderRadius: BorderRadius.circular(4),
                  boxShadow: const [
                    BoxShadow(
                        color: Color(0x0A0F499F),
                        blurRadius: 12,
                        offset: Offset(0, 0))
                  ]),
              child: DefaultTextStyle(
                style: const TextStyle(color: Colours.text, fontSize: 12),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: List.generate(
                      children.length,
                      (index) => children[index].paddingOnly(
                          bottom: (index < children.length - 1) ? 4 : 0)),
                ),
              ),
            ),
            Positioned.fill(
                child: Align(
              alignment: left ? Alignment.centerRight : Alignment.centerLeft,
              child: Container(
                width: 4,
                height: 4,
                decoration: BoxDecoration(
                    color: left ? Colours.homeColorRed : Colours.blue2766D6,
                    shape: BoxShape.circle),
              ),
            )),
          ],
        );

  Widget _timeCell(bool hasTop, bool hasBottom, List<ZqEventModel> evs) {
    // log("evs length = ${evs.length}");
    if (evs.isEmpty) {
      return Container();
    }
    final first = evs.first;
    final mid = first.eventTime;
    Widget center = Container(
        width: 40,
        height: 32,
        alignment: Alignment.center,
        child: QsText(" $mid´",
            color: Colours.grey99, fontWeight: FontWeight.w500));
    if (first.eventType == ZqEvent.banChangJieShu) {
      evs = [];
      center = Container(
          // width: 200,
          padding: const EdgeInsets.symmetric(horizontal: 8),
          height: 32,
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4),
              border: Border.all(color: Colours.grey99, width: 0.5)),
          alignment: Alignment.center,
          child: QsText(mid,
              fontSize: 12,
              color: Colours.grey99,
              fontWeight: FontWeight.w500));
    } else if (first.eventType == ZqEvent.jieShu) {
      evs = [];
      center = Container(
          width: 200,
          // height: ,
          alignment: Alignment.center,
          child: Column(children: [
            Row(
              children: [
                Expanded(child: Container()),
                Image.asset(Utils.getImgPath("match_icon_end.png"),
                    width: 20, height: 20, fit: BoxFit.fill),
                Expanded(
                    child: Container(
                  margin: const EdgeInsets.only(left: 5),
                  child: QsText("结束", color: Colours.grey99, fontSize: 12),
                )),
              ],
            ),
            const SizedBox(height: 8),
            Container(
                padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 2),
                height: 24,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(4),
                    border: Border.all(color: Colours.greyCC, width: 0.5)),
                child: QsText(mid.replaceAll("结束 ", ""),
                    color: Colours.grey99, fontWeight: FontWeight.w500))
          ]).marginSymmetric(vertical: 10));
    }

    List<ZqEventModel> leftList = [];
    List<ZqEventModel> rightList = [];
    for (var i = 0; i < evs.length; i++) {
      if (evs[i].isHome) {
        leftList.add(evs[i]);
      } else {
        rightList.add(evs[i]);
      }
    }
    return IntrinsicHeight(
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 12),
        child: Row(
          children: [
            Expanded(
                // fit: FlexFit.tight,
                child: eventSideCard([
              ...leftList.map((e) => Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      if (e.eventContent.hasValue) ...[
                        Expanded(
                            child: QsText(
                          e.eventContent ?? "",
                          maxLines: 99,
                          textAlign: TextAlign.end,
                        )),
                        const SizedBox(width: 3),
                      ],
                      ZqMilestoneUtils.getIconWithEventType(e.eventType)
                          .marginAll(2)
                    ],
                  ))
            ])),
            Column(
              children: [
                Expanded(
                    child: Container(
                  width: 1,
                  color: hasTop ? Color(0xFFEEEEEE) : Colors.transparent,
                )),
                center,
                Expanded(
                    child: Container(
                  width: 1,
                  color: hasBottom ? Color(0xFFEEEEEE) : Colors.transparent,
                )),
              ],
            ),
            Expanded(
                child: eventSideCard([
              ...rightList.map((e) => Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      ZqMilestoneUtils.getIconWithEventType(e.eventType)
                          .marginAll(2),
                      if (e.eventContent.hasValue) ...[
                        const SizedBox(width: 3),
                        Expanded(
                            child: QsText(
                          e.eventContent ?? "",
                          maxLines: 99,
                        )),
                      ],
                    ],
                  ))
            ], left: false)),
          ],
        ),
      ),
    );
  }

  Widget _top() {
    return Container(
      height: 40,
      margin: const EdgeInsets.only(right: 12),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Transform.translate(
            offset: const Offset(-2, 0),
            child: QsText("只看进球", color: Colours.grey99),
          ),
          ZqSitch(
              activeColor: Colors.red,
              value: onlyScore,
              onChanged: (v) {
                onlyScore = v;
                update();
              })
        ],
      ),
    );
  }

  Widget _iconWidget() {
    return Container(
      height: 80,
      color: Colours.white,
      alignment: Alignment.center,
      padding: EdgeInsets.symmetric(horizontal: 16),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: List.generate(
                  5,
                  (index) => Row(
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          ZqMilestoneUtils.icon[index],
                          const SizedBox(width: 5),
                          QsText(ZqMilestoneUtils.title[index],
                              fontSize: 12, height: 1)
                        ],
                      ))),
          Container(height: 10),
          Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: List.generate(
                  5,
                  (index) => Row(
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          ZqMilestoneUtils.icon[5 + index],
                          const SizedBox(width: 5),
                          QsText(ZqMilestoneUtils.title[5 + index],
                              fontSize: 12, height: 1)
                        ],
                      ))),
        ],
      ),
    );
  }
}
